<script>
import * as echarts from 'echarts'

let carbonEmissionsTrend = null
export default {
  name: 'CarbonReductionAnalysis',
  props: {
    queryParams: {
      required: false,
      default: {}
    },
    projectList: {
      required: false,
      default: []
    }
  },
  computed: {
    getProjectNames() {
      return this.projectList.filter(project => this.queryParams.sceneProjectId == null || project.value === this.queryParams.sceneProjectId)
        .map(project => project.label).join('，')
    },
    getMaxProductTypeCarbonEmissionData() {
      if (this.dataList.length > 0) {
        return this.dataList.slice().sort((a, b) => b.carbonEmission - a.carbonEmission)[0]
      }
      return {}
    },
    getMinProductTypeCarbonEmissionData() {
      if (this.dataList.length > 0) {
        return this.dataList.slice().sort((a, b) => a.carbonEmission - b.carbonEmission)[0]
      }
      return {}
    }
  },
  watch: {
    queryParams: {
      async handler(val) {
        if (val.sceneProjectId) {
          const param = {
            statisticsMode: val.statisticsMode,
            solidifyDateStart: val.startTime,
            solidifyDateEnd: val.endTime,
            sceneProjectId: val.sceneProjectId
          }
          if (val.roomInfo != null && val.roomInfo.length > 0) {
            param.sceneEdificeId = val.roomInfo[0]
            param.sceneFloorId = val.roomInfo.length > 1 ? val.roomInfo[1] : null
            param.sceneRoomId = val.roomInfo.length > 2 ? val.roomInfo[2] : null
          }
          const res = await this.$api.carbonEmissionReport.carbonReductionOverview(param)
          this.startTime = res.data.startDate
          this.endTime = res.data.endDate
          this.dataList = res.data.dataList
          const carbonReductionTrendRes = await this.$api.carbonEmissionReport.carbonReductionTrend(param)
          this.carbonReductionTrendList = carbonReductionTrendRes.data

          this.initEcharts()
        }
      },
      deep: true,
      immediate: true
    }
  },
  data() {
    return {
      startTime: null,
      endTime: null,
      dataList: [],
      carbonReductionTrendList: []
    }
  },
  destroyed() {
    this.disposeEcharts()
  },
  methods: {
    disposeEcharts() {
      carbonEmissionsTrend.dispose()
      carbonEmissionsTrend = null
    },
    getMaxTrendDataById(id) {
      if (this.carbonReductionTrendList.length > 0) {
        return this.carbonReductionTrendList.slice().sort((a, b) => b[id] || 0 - a[id] || 0)[0]
      }
      return {}
    },
    getMinTrendDataById(id) {
      if (this.carbonReductionTrendList.length > 0) {
        return this.carbonReductionTrendList.slice().sort((a, b) => a[id] || 0 - b[id] || 0)[0]
      }
      return {}
    },
    getMaxTrendPieData() {
      if (this.carbonReductionTrendList.length > 0) {
        return this.carbonReductionTrendList.slice().sort((a, b) => b.total - a.total)[0]
      }
      return {}
    },
    getMinTrendPieData() {
      if (this.carbonReductionTrendList.length > 0) {
        return this.carbonReductionTrendList.slice().sort((a, b) => a.total - b.total)[0]
      }
      return {}
    },
    initEcharts() {
      this.$nextTick(() => {
        if (carbonEmissionsTrend == null) {
          carbonEmissionsTrend = echarts.init(document.getElementById('carbonEmissionsTrend'))
        }
        carbonEmissionsTrend.setOption({
          xAxis: {
            type: 'category',
            data: this.carbonReductionTrendList.map(item => item.solidifyDate)
          },
          yAxis: {
            type: 'value',
            name: '碳减趋势（kgCO2）'
          },
          series: [
            {
              data: this.carbonReductionTrendList.map(item => item.total),
              type: 'line'
            }
          ]
        })
      })
    }
  }
}
</script>

<template>
  <div>
    <h2>06 碳减情况分析</h2>
    <div class="analysis-box">
      <div>
        <h3>6.1 碳减总览</h3>
        <table style="width: 60%; margin: 0 15%">
          <thead>
          <tr>
            <th>产品类型</th>
            <th>计量值</th>
            <th>碳减排量（kgCO2）</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="item in dataList" :key="item.id">
            <td>{{ item.productTypeName }}</td>
            <td>{{ item.meterValue }}</td>
            <td>{{ item.carbonEmission }}</td>
          </tr>
          <tr>
            <td>合计综合</td>
            <td>
              {{ dataList.map(item => item.meterValue).reduce((accumulator, currentValue) => accumulator + currentValue, 0)
              }}
            </td>
            <td>
              {{ dataList.map(item => item.carbonEmission).reduce((accumulator, currentValue) => accumulator + currentValue, 0)
              }}
            </td>
          </tr>
          </tbody>
        </table>
        <div style="margin: 0 15%">
          <p>展示不同类型产品在特定时间段内的碳减排量。{{ getProjectNames }}在 {{ startTime }}- {{ endTime }}日中，
            碳减排总量为{{ dataList.map(item => item.carbonEmission).reduce((accumulator, currentValue) => accumulator + currentValue, 0)
            }} kgCO2；
            {{ getMaxProductTypeCarbonEmissionData.productTypeName }}的碳减排量最高，为
            {{ getMaxProductTypeCarbonEmissionData.carbonEmission }} kgCO2;
            {{ getMinProductTypeCarbonEmissionData.productTypeName }}的碳减排量最低，为
            {{ getMinProductTypeCarbonEmissionData.carbonEmission }} kgCO2。</p>
        </div>
      </div>
      <div>
        <h3>6.2 碳减趋势</h3>
        <div class="carbon-emissions-trend">
          <div id="carbonEmissionsTrend"
               style="width: 100%;height: 300px;background-color: rgba(2, 149, 144, 0.1);"></div>
          <div>
            <div class="desc">
              <p>展示在特定时间段内碳减的变化趋势。{{ getProjectNames }}在 {{ startTime }}- {{ endTime }}中，{{ getMaxTrendPieData.solidifyDate }}的碳减排量最高，为
                {{ getMaxTrendPieData.total }} kgCO2;{{ getMinTrendPieData.solidifyDate }}碳减排量最低，为 {{ getMinTrendPieData.total }} kgCO2。</p>
            </div>
            <table>
              <thead>
              <tr>
                <th>数据时间</th>
                <th v-for="item in dataList" :key="item.id">{{ item.productTypeName }}</th>
                <th>总量</th>
              </tr>
              </thead>
              <tbody>
              <tr v-for="(trendItem,index) in carbonReductionTrendList" :key="`${trendItem.solidifyDate}_${index}`">
                <td>{{ trendItem.solidifyDate }}</td>
                <td v-for="item in dataList" :key="item.id">{{ trendItem[item.id] || 0 }}</td>
                <td>{{ trendItem.total }}</td>
              </tr>
              </tbody>
            </table>
            <div class="desc">
              <p>展示和分析在时间段内不同产品类型的碳减量。{{ getProjectNames }}在 {{ startTime }}- {{ endTime }}中，
                <span v-for="item in dataList" :key="item.id">
                  {{  item.productTypeName }}碳减总量为{{ carbonReductionTrendList.map(trend => trend[item.id] || 0).reduce((accumulator, currentValue) => accumulator + currentValue, 0) }} kgCO2，
                  其中{{ getMaxTrendDataById(item.id).solidifyDate }}的 {{ item.productTypeName }}碳减量最高，
                  为 {{ getMaxTrendDataById(item.id)[item.id] || 0 }} kgCO2;
                  {{ getMinTrendDataById(item.id).solidifyDate }}的{{ item.productTypeName }}碳减量最低，为 {{ getMinTrendDataById(item.id)[item.id] || 0 }} kgCO2。
                </span></p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.analysis-box {
  margin: 0 5%;

  table {
    border-collapse: collapse;
    width: 80%;
    margin: 0 10%;
    font-size: 16px;
    font-weight: 500;

    th {
      border: 1px solid rgba(0, 0, 0, 0.6);
      padding: 6px 10px;
      background-color: rgb(2, 149, 144);
      text-align: center;
    }

    td {
      border: 1px solid #000000;
      padding: 6px 10px;
      text-align: center;
    }
  }

  .carbon-emissions-trend {
    margin: 0 15%;
  }

  p {
    text-indent: 2em;
    line-height: 24px;
  }
}
</style>
